package com.snopy.socket;

import lombok.extern.slf4j.Slf4j;

import javax.net.ServerSocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;

/**
 * @author snopy
 * @version 1.0.0
 * @classname SSLSocketService
 * @description
 * @email 77912204@qq.com
 * @date 2022/06/11 9:46
 */
@Slf4j
public class SSLSocketService {
    private String SERVER_KEY_STORE = "E:/cas_sso.keystore";
    private String SERVER_KEY_STORE_PASSWORD = "123456";
    private SSLServerSocket createSSLServerSocket() throws Exception{
        // whether enable the debug mode
        System.setProperty("javax.net.debug", "ssl,handshake");
        System.setProperty("javax.net.ssl.trustStore", SERVER_KEY_STORE);
        SSLContext context = SSLContext.getInstance("TLS");

        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(SERVER_KEY_STORE), SERVER_KEY_STORE_PASSWORD.toCharArray());
        KeyManagerFactory kf = KeyManagerFactory.getInstance("SunX509");
        kf.init(ks, SERVER_KEY_STORE_PASSWORD.toCharArray());
        context.init(kf.getKeyManagers(), null, null);

        ServerSocketFactory factory = context.getServerSocketFactory();
        ServerSocket serverSocket = factory.createServerSocket(443);
        SSLServerSocket sslServerSocket =  (SSLServerSocket) serverSocket;
        // set whether need the client authentication
//        sslServerSocket.setNeedClientAuth(true);
        return sslServerSocket;
    }
    private void start() throws Exception{
        SSLServerSocket sslServerSocket= createSSLServerSocket();

        while(true){
            try{
                Socket socket = sslServerSocket.accept();
                InputStream is = socket.getInputStream();
                byte[] bytes = new byte[Short.MAX_VALUE];
                int len = -1;

                while((len = is.read(bytes))>0){
                    log.info(new String(bytes,0,len));
                    if(len<bytes.length){
                        break;
                    }
                }
                socket.getOutputStream().write("server balabala ... ".getBytes());
                socket.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new SSLSocketService().start();
    }

}
